package com.kaisu.blog.web.config;

import com.kaisu.blog.application.properties.AuthProperties;
import com.kaisu.blog.application.user.service.JWTService;
import com.kaisu.blog.application.user.service.impl.UserServiceImpl;
import com.kaisu.blog.domain.user.repository.UserRepository;
import com.kaisu.blog.web.filter.JWTAuthenticationFilter;
import com.kaisu.blog.web.handler.JwtAccessDeniedHandler;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
@EnableMethodSecurity
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class WebSecurityConfig {

    private final UserServiceImpl userService;
    private final UserRepository userRepository;
    private final AuthProperties authProperties;
    private final AuthenticationConfiguration authenticationConfiguration;
    private final JWTService jwtService;
    private final JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        //1. 添加 CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOriginPattern("*");
        //是否发送 Cookie
        config.setAllowCredentials(true);
        //放行哪些请求方式
        config.addAllowedMethod("*");
        //放行哪些原始请求头部信息
        config.addAllowedHeader("*");
        //暴露哪些头部信息
        config.addExposedHeader("*");
        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        return corsConfigurationSource;
    }

    @Bean
    SecurityFilterChain filterChain(@NotNull HttpSecurity http) throws Exception {
        List<String> permitMethods = authProperties.getPermitMethod();
        String[] permitMethodArray = permitMethods.toArray(String[]::new);
        return http
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(permitMethodArray).permitAll()
                        .requestMatchers(authProperties.getPrefix().concat("/**")).authenticated()
                        .anyRequest().permitAll()
                )
                .addFilter(new JWTAuthenticationFilter(authenticationConfiguration.getAuthenticationManager(), userRepository, jwtService))
                .exceptionHandling(exceptionHandling -> {
                    exceptionHandling.accessDeniedHandler(jwtAccessDeniedHandler);
                    exceptionHandling.authenticationEntryPoint(jwtAccessDeniedHandler);
                })
                .userDetailsService(userService)
                .build();
    }
}